package com.cofdet.modbusdebugger;

import android.content.Intent;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;

/**
* Created by Jason on 2016/5/18.
*/
public class UdpServer implements Runnable {
    private int SlvCount = 0;//客户端数量
    private String ip = null;
    private int port = 0;
    private DatagramPacket dpRcv = null,dpSend = null;
    private static DatagramSocket ds = null;
    private InetSocketAddress inetSocketAddress = null;
    private byte[] msgRcv = new byte[4096];
    private boolean udpLife = true;     //udp生命线程
    private boolean udpLifeOver = true; //生命结束标志，false为结束

    private final ModbusCfg modbusCfg;

    public UdpServer(String mIp, int mPort, ModbusCfg modbusCfg) {
        //this.ip  = "192.168.88.212";//测试时
        this.ip = mIp;
        this.port = mPort;
        this.modbusCfg = modbusCfg;
    }
    public boolean haveSlv(){return SlvCount != 0; }


    private void SetSoTime(int ms) throws SocketException {
        ds.setSoTimeout(ms);
    }

    //返回udp生命线程因子是否存活
    public boolean isUdpLife(){
        return udpLife;
    }

    //返回具体线程生命信息是否完结
    public boolean IsUdpLifeOver(){
        return udpLifeOver;
    }

    //更改UDP生命线程因子
    public void setUdpLife(boolean b){
        udpLife = b;
    }

    public void Send(String msg){
        try {
            ByteBuffer wrBuf = ByteBuffer.allocate(4096);
            modbusCfg.SendPro(wrBuf, msg);

            Log.i("SocketInfo","客户端IP："+ dpRcv.getAddress().getHostAddress() +"客户端Port:"+ dpRcv.getPort());
            dpSend = new DatagramPacket(wrBuf.array(), wrBuf.limit(), dpRcv.getAddress(),dpRcv.getPort());
            ds.send(dpSend);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        inetSocketAddress = new InetSocketAddress(ip, port);
        try {
            ds = new DatagramSocket(port);
            Log.i("SocketInfo", "UDP服务器已经启动");

            SetSoTime(3000);//设置超时，不需要可以删除

        } catch (SocketException e) {
            e.printStackTrace();
        }

        dpRcv = new DatagramPacket(msgRcv, msgRcv.length);
        while (udpLife) {
            try {
                Log.i("SocketInfo", "UDP监听中");
                ds.receive(dpRcv);
                //收到后,
                if(SlvCount == 0){//这里应用map比较是否为新的客户端,暂只认为是一个
                    SlvCount++;
                    String curIp = dpRcv.getAddress().getHostAddress().toString();
                    Log.i("SocketInfo", "SocketInfo:检测到新的客户端联入,ip:" + curIp);
                    //推送到主界面
                    Intent intent =new Intent();
                    intent.setAction("tcpServerReceiver");
                    intent.putExtra("tcpServerReceiver",
                            "\n<-----IP: " + curIp +" 已接入----->");
                    FuncTcpServer.context.sendBroadcast(intent);//将消息发送给主界面
                }
                System.arraycopy(msgRcv, dpRcv.getOffset(), msgRcv, 0, dpRcv.getLength());//去掉前缀
                String rcvMsg = "Rx: " + modbusCfg.RcvPro(msgRcv, dpRcv.getLength());
                Log.i("SocketInfo", rcvMsg);
                Intent intent = new Intent();
                intent.setAction("tcpServerReceiver");
                intent.putExtra("tcpServerReceiver", rcvMsg);
                FuncTcpServer.context.sendBroadcast(intent);//将消息发送给主界面

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ds.close();
        Log.i("SocketInfo","UDP监听关闭");
        //udp生命结束
        udpLifeOver = false;
    }
}
